package cn.fx.pet.service.impl;

import cn.fx.basic.exception.BusinessException;
import cn.fx.basic.service.IBaiduAiAuditService;
import cn.fx.basic.service.impl.BaseServiceImpl;
import cn.fx.basic.util.CodeGenerateUtils;
import cn.fx.basic.util.DistanceUtils;
import cn.fx.basic.util.PageList;
import cn.fx.basic.util.Point;
import cn.fx.order.domain.OrderPetAcquisition;
import cn.fx.order.mapper.OrderPetAcquisitionMapper;
import cn.fx.org.domain.Employee;
import cn.fx.org.domain.Shop;
import cn.fx.org.mapper.EmployeeMapper;
import cn.fx.org.mapper.ShopMapper;
import cn.fx.pet.domain.Pet;
import cn.fx.pet.domain.SearchMasterMsg;
import cn.fx.pet.domain.SearchMasterMsgAuditLog;
import cn.fx.pet.dto.AcceptDto;
import cn.fx.pet.mapper.PetMapper;
import cn.fx.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.fx.pet.mapper.SearchMasterMsgMapper;
import cn.fx.pet.query.SearchMasterMsgQuery;
import cn.fx.pet.service.ISearchMasterMsgService;

import cn.fx.user.domain.User;
import cn.fx.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * (SearchMasterMsg)表服务实现类
 *
 * @author makejava
 * @since 2022-08-09 11:16:58
 */
@Service
//查询的方法比较多，使用查询的事务配置
//只读，事务传播机制=SUPPORTS，有我就用，没有事务就不用
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService  {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Override
    public void publish(SearchMasterMsg smm, Long id){

        //先添加到数据库t_searchMasterMsg ,通过logininfoid查询userid
        User user = userMapper.loadByLogininfoId(id);
        smm.setUserId(user.getId());
        baiduAiAuditService.textAudit("待审核！");

        //shop_id: 先计算最近店铺 获取当前地址的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShopId(nearestShop.getId());

        searchMasterMsgMapper.save(smm);

        //审核文本
        Boolean textAudit = baiduAiAuditService.textAudit(smm.getTitle() + smm.getName() + smm.getAddress() + smm.getNote());
        Boolean imageAudit = baiduAiAuditService.imageAudit(smm.getResources());

        if(textAudit){
            //审核通过  修改状态
            smm.setState(1);
            smm.setNote("待处理！");
            searchMasterMsgMapper.update(smm);

            //添加审核日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsgId(smm.getId());
            smmal.setState(1);
            smmal.setAuditTime(new Date());
            smmal.setNote("待处理状态！");
            //保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            //短信
        } else {
            //审核通过  修改状态
            smm.setNote("驳回，信息异常");
            searchMasterMsgMapper.update(smm);

            //添加审核日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsgId(smm.getId());
            smmal.setState(0);
            smmal.setAuditTime(new Date());
            smmal.setNote("审核不通过");
            //保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常,请重新录入");
        }
    }

    /**
     * 待处理
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        //通过logininfo查询employee
        Employee emp = employeeMapper.loadByLogininfoId(id);
        //待处理状态
        query.setState(1);
        if(emp.getShop_id() != null){
            query.setShopId(emp.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 查询到用户id
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query,Long id) {
        //查询到用户id
        User user = userMapper.loadByLogininfoId(id);
        query.setUserId(user.getId());

        return super.pageQuery(query);
    }

    @Override
    public void reject(Long id) {

        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param dto
     * @param id
     */
    @Override
    public void accept(AcceptDto dto, Long id) {

        Long handler = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();

        //根据是smmid查询订单，查得到，该订单正在处理中
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if(order != null){//之前接单了
            throw new BusinessException("订单正在处理中....!");
        }

        //生成一个pet: 根据searchMasterMsg生成
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        //生成一个收购订单
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        //保存id
        petMapper.save(pet);
        //生成一个收购订单
        OrderPetAcquisition opa = ininOrderPetAcquisition(dto,pet,searchMasterMsg);
        //保存订单
        orderPetAcquisitionMapper.save(opa);
    }

    /**
     * 生成一个订单对象
     * @param dto
     * @param pet
     * @return
     */
    private OrderPetAcquisition ininOrderPetAcquisition(AcceptDto dto, Pet pet,SearchMasterMsg smm) {

        //创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();
        System.out.println(smm.getUserId());
        //随机生成一个订单编号
        order.setOrdersn(CodeGenerateUtils.generateOrderSn(smm.getUserId()));
        //摘要
        order.setDigest("【" + smm.getTitle() + "】");
        //最后确认时间  定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        
        order.setState(0);//待处理
        order.setPrice(smm.getPrice());
        order.setPetId(pet.getId());
        order.setUserId(smm.getUserId());
        order.setShopId(smm.getShopId());
        order.setAddress(smm.getAddress());
        order.setEmpId(dto.getHandler());
        order.setSearchMasterMsgId(dto.getMsgId());
        return order;
    }

    /**
     * 通过searchMasterMsg 生成一个pet
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
       
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShopId());
        pet.setSearch_master_msg_id(smm.getId());

        return pet;

    }


    /**
     * 无极限树
     *
     * @author makejava
     * @since 2022-08-06 18:34:41
     */
     @Override
    public List<SearchMasterMsg> deptTree() {
      
        //查询所有
        /*List<SearchMasterMsg> all = searchMasterMsgMapper.loadAll();

        //准备一个map 每次获取父部门都从这里获取
        HashMap<Long, SearchMasterMsg> map = new HashMap<>();

        //把所有数据放入map中
        for (SearchMasterMsg searchMasterMsg : all){
            map.put(searchMasterMsg.getId(),searchMasterMsg);
        }

        //准备一个list，保存处理之后的数据: 前端需要得到的集合数据 - 部门树
        List<SearchMasterMsg> deptTree = new ArrayList<>();
        for(SearchMasterMsg searchMasterMsg : all){
            //顶级部门
            if( == null){
                deptTree.add(searchMasterMsg);
            } else {
                //不是顶级部门  1.想办法找到当前部门的 父部门  获取parent_id
                Long parent_id = searchMasterMsg.getParent_id();

                //获取上级部门对象: 通过parent_id来找到上级部门, map里面有所有信息
                SearchMasterMsg parentSearchMasterMsg = map.get(parent_id);

                //2.将自己装到  父部门 的children中
                parentSearchMasterMsg.getChildren().add(searchMasterMsg);
            }
        }
        //返回部门树
        return deptTree;*/
        return null;
    }

}
